package mock_seed

import (
	"fmt"
	"wms/internal/model"
	"wms/pkg/database"
	"wms/pkg/logger"
	"wms/pkg/utils"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// InitWarehousesAndLocations 初始化仓库和库位模拟数据（冷链冻品仓库及库位）
func InitWarehousesAndLocations() error {
	db := database.GetDB()
	logger.Info("开始初始化冷链仓库和库位模拟数据...")

	warehouses := []model.Warehouse{
		{
			Name:           "冷冻肉类库",
			Code:           "FL001",
			Type:           "冷冻",
			Area:           utils.Float64Ptr(1200.00),
			Capacity:       utils.IntPtr(600),
			MinTemperature: utils.Float64Ptr(-25.0),
			MaxTemperature: utils.Float64Ptr(-18.0),
			MinHumidity:    utils.Float64Ptr(85.0),
			MaxHumidity:    utils.Float64Ptr(95.0),
			Status:         1,
			Remark:         "专业肉类冷冻仓库，适合各类肉制品长期保存",
		},
		{
			Name:           "水产冷冻库",
			Code:           "FL002",
			Type:           "冷冻",
			Area:           utils.Float64Ptr(800.00),
			Capacity:       utils.IntPtr(400),
			MinTemperature: utils.Float64Ptr(-22.0),
			MaxTemperature: utils.Float64Ptr(-18.0),
			MinHumidity:    utils.Float64Ptr(80.0),
			MaxHumidity:    utils.Float64Ptr(90.0),
			Status:         1,
			Remark:         "水产品冷冻库，适合海鲜和水产品保存",
		},
		{
			Name:           "速冻食品库",
			Code:           "FL003",
			Type:           "冷冻",
			Area:           utils.Float64Ptr(1000.00),
			Capacity:       utils.IntPtr(500),
			MinTemperature: utils.Float64Ptr(-20.0),
			MaxTemperature: utils.Float64Ptr(-18.0),
			MinHumidity:    utils.Float64Ptr(80.0),
			MaxHumidity:    utils.Float64Ptr(90.0),
			Status:         1,
			Remark:         "速冻食品专用库，适合各类速冻成品",
		},
	}

	// 库位编码和名称
	locationDataList := []struct {
		WarehouseCode string
		Code          string
		Name          string
		Type          string
		Capacity      int
		Status        int
		Remark        string
	}{
		// 冷冻肉类库 - 5个库位
		{"FL001", "A-01-01", "牛肉区货架1位", "存储区", 40, 1, "牛肉产品冷冻库位"},
		{"FL001", "A-02-01", "牛肉区货架2位", "存储区", 40, 1, "牛肉产品冷冻库位"},
		{"FL001", "B-01-01", "猪肉区货架1位", "存储区", 45, 1, "猪肉产品冷冻库位"},
		{"FL001", "B-02-01", "猪肉区货架2位", "存储区", 45, 1, "猪肉产品冷冻库位"},
		{"FL001", "FL001-R-01", "肉类收货区", "收货区", 50, 1, "肉类产品入库缓存区"},

		// 水产冷冻库 - 5个库位
		{"FL002", "C-01-01", "鱼类区货架1位", "存储区", 35, 1, "冷冻鱼类存储位"},
		{"FL002", "C-02-01", "鱼类区货架2位", "存储区", 35, 1, "冷冻鱼类存储位"},
		{"FL002", "D-01-01", "虾蟹区货架1位", "存储区", 30, 1, "冷冻虾蟹存储位"},
		{"FL002", "D-02-01", "虾蟹区货架2位", "存储区", 30, 1, "冷冻虾蟹存储位"},
		{"FL002", "FL002-R-01", "水产收货区", "收货区", 40, 1, "水产品入库缓存区"},

		// 速冻食品库 - 5个库位
		{"FL003", "E-01-01", "成品区货架1位", "存储区", 50, 1, "速冻食品成品存储"},
		{"FL003", "E-02-01", "成品区货架2位", "存储区", 50, 1, "速冻食品成品存储"},
		{"FL003", "F-01-01", "半成品区货架1位", "存储区", 45, 1, "速冻食品半成品存储"},
		{"FL003", "F-02-01", "半成品区货架2位", "存储区", 45, 1, "速冻食品半成品存储"},
		{"FL003", "FL003-S-01", "速冻发货区", "发货区", 50, 1, "速冻食品出库暂存区"},
	}

	// 使用事务确保原子性
	return db.Transaction(func(tx *gorm.DB) error {
		warehouseMap := make(map[string]uint) // 用于存储仓库Code和ID的映射

		// 1. 创建仓库
		for i := range warehouses {
			// 使用 FirstOrCreate 避免重复创建
			result := tx.Where("code = ?", warehouses[i].Code).FirstOrCreate(&warehouses[i])
			if result.Error != nil {
				logger.Error("创建或查找仓库失败", zap.Error(result.Error), zap.String("code", warehouses[i].Code))
				return result.Error
			}
			warehouseMap[warehouses[i].Code] = warehouses[i].ID // 记录ID
			if result.RowsAffected > 0 {
				logger.Info("仓库已创建", zap.String("name", warehouses[i].Name), zap.Uint("id", warehouses[i].ID))
			} else {
				logger.Info("仓库已存在", zap.String("name", warehouses[i].Name), zap.Uint("id", warehouses[i].ID))
			}
		}

		// 2. 创建库位
		totalCreated := 0             // 跟踪已创建的库位总数
		locationDetails := []string{} // 用于记录创建的库位详情

		for _, locData := range locationDataList {
			whID, exists := warehouseMap[locData.WarehouseCode]
			if !exists {
				logger.Warn("找不到对应的仓库", zap.String("warehouseCode", locData.WarehouseCode))
				continue
			}

			// 从库位编码中提取区域、货架、层级信息
			// 对于特殊格式如"FL001-R-01"，单独处理
			var area, shelf, level string
			if len(locData.Code) >= 6 {
				if len(locData.Code) >= 9 && locData.Code[5] == '-' { // 匹配 FL001-R-01 格式
					area = locData.Code[6:7]
					shelf = locData.Code[8:10]
					level = "01" // 默认层级
				} else { // 匹配 A-01-01 格式
					area = locData.Code[:1]
					shelf = locData.Code[2:4]
					level = locData.Code[5:7]
				}
			}

			location := model.Location{
				WarehouseID: whID,
				Code:        locData.Code,
				Name:        locData.Name,
				Type:        locData.Type,
				Area:        area,
				Shelf:       shelf,
				Level:       level,
				Capacity:    utils.IntPtr(locData.Capacity),
				Status:      locData.Status,
				Remark:      locData.Remark,
			}

			// 使用 FirstOrCreate 避免重复创建库位
			result := tx.Where("warehouse_id = ? AND code = ?", whID, locData.Code).FirstOrCreate(&location)
			if result.Error != nil {
				logger.Error("创建或查找库位失败", zap.Error(result.Error), zap.String("code", locData.Code))
				return result.Error
			}
			if result.RowsAffected > 0 {
				totalCreated++
				locationDetails = append(locationDetails, fmt.Sprintf("库位：%s (仓库：%s)", locData.Code, locData.WarehouseCode))
				logger.Info("库位已创建", zap.String("code", locData.Code), zap.Uint("warehouseId", whID))
			}
		}

		logger.Info("仓库和库位初始化成功",
			zap.Int("仓库数量", len(warehouseMap)),
			zap.Int("创建库位数量", totalCreated))

		// 输出所有创建的库位详情
		for _, detail := range locationDetails {
			logger.Debug(detail)
		}

		return nil // 事务提交
	})
}
